package run.bottle.shiro.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import run.bottle.shiro.model.entity.SysUser;
import run.bottle.shiro.service.SysUserService;
import run.bottle.shiro.utils.JWTUtil;
import run.bottle.shiro.utils.RedisUtil;
import java.util.HashSet;
import java.util.List;
/**
 * 用户认证
 * @author: lycheng
 * @date: 2020/7/21 21:14
 */
public class UserRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SysUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 获取授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("权限认证 token:" + principalCollection.toString());
        String username = JWTUtil.getUsername(principalCollection.toString());
        logger.info("用户名:" + username);
        SimpleAuthorizationInfo info = (SimpleAuthorizationInfo) redisUtil.get("authInfo_" + username);
        if (info == null) {
            SysUser user = userService.getUser(username);
            List<String> rolesSet = userService.listUserRoles(user.getUserId());
            List<String> permsSet = userService.listUserPerms(user.getUserId());
            info = new SimpleAuthorizationInfo();
            info.setRoles(new HashSet<>(rolesSet));
            info.setStringPermissions(new HashSet<>(permsSet));
            redisUtil.set("authInfo_" + username, info);
        }
        info.getRoles().forEach(role -> logger.info("用户名:" + username + " 角色->" + role));
        return info;
    }

    /**
     * 获取认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        logger.info("身份认证 token:" + token);
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        logger.info("用户名:" + username);
        if (username == null || !JWTUtil.verify(token, username)) {
            logger.info("token认证失败！");
            throw new AuthenticationException("token认证失败！");
        }
        SysUser user = userService.getUser(username);
        if (user == null) {
            logger.info("账户不存在！");
            throw new UnknownAccountException("账户不存在！");
        }
        logger.info("认证成功！");
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
